#!/bin/sh


#export > /tmp/varrssh.log
#export NAGIOS__HOSTSSH_SOCKET='/usr/local/nagios/nagssh/var/%r@%h:%p.sock'
#export NAGIOS_HOSTADDRESS='192.168.2.100'
#export NAGIOS__SERVICESSH_PASVHANDLER='logger'
#export NAGIOS__SERVICESSH_PIDFILE='/usr/local/nagios/nagssh/var/test.pid'
#export NAGIOS_SERVICEOUTPUT='ceci est un output'
#export NAGIOS_SERVICESTATE='OK'
#export NAGIOS_SERVICESTATEID='0'

REPOSITORY=/usr/local/nagios/nagssh/libexec/remote

SCRIPT=$1
shift

#pidfile=$NAGIOS__SERVICESSH_PIDFILE

#Test to see if ssh process is already alive
case `pgrep -fc "ssh -qn -o ControlPath=$NAGIOS__HOSTSSH_SOCKET $NAGIOS_HOSTADDRESS $SCRIPT $*"` in
 1 )
    #Preserve last status
    echo "$NAGIOS_SERVICEOUTPUT"
    exit "$NAGIOS_SERVICESTATEID"
    ;;
 0 )
    #process obviously not running, spawn new
    #master socket available ?
    msg=`ssh -o ControlPath=$NAGIOS__HOSTSSH_SOCKET -O check $NAGIOS_HOSTADDRESS 2>&1`
    ret=$?
    msg=`echo $msg|tr '\n' ' '`

    if [ $ret -eq 255 ]
    then
	echo "UNKNOWN - Could not access SSH master socket : $msg"
	exit 3
    fi

    #spawn background process
    #ssh -qn -o ControlPath=$NAGIOS__HOSTSSH_SOCKET $NAGIOS_HOSTADDRESS "$SCRIPT $*"  2>&1 | $NAGIOS__SERVICESSH_PASVHANDLER &
    ssh -qn -o ControlPath=$NAGIOS__HOSTSSH_SOCKET $NAGIOS_HOSTADDRESS "$SCRIPT $*"  2>&1 | "$NAGIOS__SERVICESSH_PASVHANDLER" &

    echo "OK - Service passive checking started"
    exit 0
    ;;
 * )

    echo "UNKNOWN - Check ssh process"
    exit 3
    ;;
esac

echo "HOULA"
exit 142

